//导入express模块
const express = require('express')
//创建router路由
const router = express.Router()
//导入path模块
const path = require('path')
//结构data中导出的对应数据
const { users, onlines } = require('../api/data')
//导入工具模块
const captcha = require('./utils')
//设置基本路径
const BASE_DIR = path.join(__dirname, '../views/user')
//登陆页面
router.get('/login', (req, res) => {
    res.render(path.join(BASE_DIR, 'login'), {
        msg: ''
    })
})
// 请求刷新验证码
router.use('/captcha', captcha)
//用户登录
router.post('/login', (req, res) => {
//结构请求内容
    let { username, password } = req.body
    //判断是否与data中用户数据一致
    for (let u of users) {
        if (u.username == username && u.password == password) {
        //验证成功，判断在线用户中是否有该用户
            if (onlines.indexOf(u.nickname) < 0) {
            //将该用户添加到数组中
                onlines.push(u.nickname)
            }
            //会话跟踪
            req.session.login = u
            //返回首页，渲染数据
            return res.render(path.join(BASE_DIR, 'index'), {
                    req,
                    onlines: onlines.length
                })
                // return res.redirect(path.join(BASE_DIR, '../user/index'))
        }
    }
    return res.render(path.join(BASE_DIR, 'login'), {
        msg: '用户名或者密码错误，无法正常登录'
    })
})
//首页路由，展示在线人数
router.get('/index', (req, res) => {
    res.render(path.join(BASE_DIR, 'index'), {
        req,
        onlines: onlines.length,

    })
})
//退出功能
router.get('/logout', (req, res) => {
    var index = onlines.indexOf(req.session.login.nickname)
    onlines.splice(index, 1)
    req.session.login = null
    return res.render(path.join(BASE_DIR, 'login'), {
        msg: '退出成功'
    })

})
//注册页面
router.get('/register', (req, res) => {
    return res.render(path.join(BASE_DIR, 'register'), {
        msg: ''
    })

})
//注册请求
router.post('/register', (req, res) => {
    let { username, password, cofrim, nickname, captcha } = req.body
    for (let u of users) {
		//判断用户是否已被注册
        if (username == u.username) {
            return res.render(path.join(BASE_DIR, '/register'), {
                msg: '用户名已被注册，换一个试试'
            })
        }
        if (password != cofrim) {
            return res.render(path.join(BASE_DIR, '/register'), {
                msg: '两次密码输入不一致'
            })
        }
        if (captcha.toUpperCase() != req.session.captcha.toUpperCase()) {
            return res.render(path.join(BASE_DIR, '/register'), {
                msg: '验证码错误'
            })
        }
        //注册成功，将新用户添加到用户数组中
        let newuser = { username, password, nickname }
        users.push(newuser)

        return res.render(path.join(BASE_DIR, '/login'), {
            msg: '注册成功，前往登录'
        })

    }
})
//导出user模块
module.exports = {
    router
}
